package repository;

import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.inject.Inject;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by jack on 18/6/1.
 */
@Repository
public class JdbcUserRepository {

    //id user_name password   id是自增的
    private static final String INSERT_USER = "INSERT INTO user values(NULL, ?, ?)";
    private static final String SELECT_USER_BY_NAME = "SELECT (user_name, password) from user where name = ?";
    private JdbcOperations jdbcOperations;

    @Inject
    public JdbcUserRepository(JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }

    /*添加一个User*/
    public void addUser(User user){
        jdbcOperations.update(INSERT_USER,
                user.getUser_name(),
                user.getPassword());
    }

    /*查找一个人*/
    public User findOne(String userName){
        return jdbcOperations.queryForObject(SELECT_USER_BY_NAME,
                new UserRowMapper(),
                userName);
    }

    private static final class UserRowMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet rs, int i) throws SQLException {
            return new User(rs.getString("user_name"),rs.getString("password"));
        }
    }

}
